<template>
    <view class="pb-160">
        <image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }"
            mode="aspectFill"></image>
        <u-navbar title="检验判定标准添加" :autoBack="true" leftIconColor="#fff" bgColor="transparent"
            :titleStyle="{ color: '#fff' }" safeAreaInsetTop placeholder></u-navbar>

        <view class="w-710 mt-20 bgff br-20 ml-20 pl-32 pr-32">
            <view class="rowsb rowsm h-100 bor-b" @tap="showYearPicker = true">
                <view>年份</view>
                <view class="trt fs-28 col999 rowsc rowsm" v-if="!formData.year">请选择
                    <u-icon name="arrow-right" size="17" color="#999" style="vertical-align: top;"></u-icon>
                </view>
                <view class="trt fs-28" v-else>{{ formData.year }}</view>
            </view>
            <view class="rowsb rowsm h-100 bor-b" @tap="showTypePicker = true">
                <view>检测类型</view>
                <view class="trt fs-28 col999 rowsc rowsm" v-if="!formData.detectionType">请选择
                    <u-icon name="arrow-right" size="17" color="#999" style="vertical-align: top;"></u-icon>
                </view>
                <view class="trt fs-28" v-else>{{ formData.detectionTypeLabel || formData.detectionType }}</view>
            </view>
            <!-- <view class="rowsb rowsm h-100 bor-b" @tap="showProductPicker = true">
                <view>产品名称</view>
                <view class="trt fs-28 col999 rowsc rowsm" v-if="!formData.productName">请选择
                    <u-icon name="arrow-right" size="17" color="#999" style="vertical-align: top;"></u-icon>
                </view>
                <view class="trt fs-28" v-else>{{ formData.productName }}</view>
            </view> -->
            <!-- 判定标准上传 -->
            <view class="rowsb rowsm bor-b">
                <view>判定标准上传：</view>
                <view class="trt fs-28">
                    <view class="upload-section">
                        <u-button type="primary" size="small" @click="handleUpload">点击上传</u-button>
                        <text class="upload-note">注:支持.xlsx、xls、docx文件</text>

                        <!-- 已上传文件列表 -->
                        <view v-if="uploadedFiles.length > 0" class="file-list">
                            <view v-for="(file, index) in uploadedFiles" :key="index" class="file-item">
                                <view class="file-info">
                                    <u-icon name="file-text" size="32" color="#007AFF"></u-icon>
                                    <text class="file-name">{{ file.name }}</text>
                                    <text class="file-size">{{ formatSize(file.size) }}</text>
                                </view>
                                <view class="file-status">
                                    <text v-if="file.status === 'success'" class="status-success">{{
                                        getStatusText(file.status) }}</text>
                                    <text v-else-if="file.status === 'progress'" class="status-progress">{{
                                        getStatusText(file.status) }} {{ file.progress }}%</text>
                                    <text v-else-if="file.status === 'fail'" class="status-fail">{{
                                        getStatusText(file.status) }}</text>
                                    <text v-else class="status-pending">{{ getStatusText(file.status) }}</text>
                                </view>
                                <u-icon name="close" size="24" color="#999" @click="removeFile(index)"></u-icon>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 上传后显示的检测标准列表 -->
        <view v-if="detectionStandards.length > 0" class="w-710 mgt bgff pl-20 pr-20 br-20 pt-24 pb-24">
            <!-- 遍历每个产品 -->
            <view v-for="(productName, index) in productNames" :key="index" class="product-section">
                <view class="rowsb rowsm">
                    <view class="rows rowsm">
                        <image src="/static/icon_bl.png" class="w-40 h-40 mr-20" mode="aspectFill"></image>
                        <view class="">{{ productName }}</view>
                    </view>
                    <view class="rowsc rowsm br-32 w-84 h-48" style="background-color: #FF8C34;color: #fff;"
                        @click="addItem(productName)">添加</view>
                </view>

                <!-- 遍历该产品的检测项目 -->
                <view v-for="(item, itemIndex) in groupedStandards[productName]" :key="itemIndex"
                    class="w-670 pl-24 pr-24 pt-24 mgt" style="background: #F7F7F7;">
                    <view class="fs-28 fw-b rowsb rowsm pb-16">
                        <view class="rows rowsm">
                            <text class="mr-10">{{ item.serialNumber }}.检测项目:</text>
                            <input class="fs-28 fw-b" v-model="item.inspectionItem" placeholder="请输入检测项目" />
                        </view>
                        <image src="/static/icon_s.png" class="w-32 h-32 mr-20" mode="aspectFill"
                            @click="deleteItem(item, itemIndex, productName)"></image>
                    </view>
                    <view class="rows rowsm pb-16">
                        <view class="col888 fs-26 fw-500 mr-10">限量值(mg/kg):</view>
                        <input class="fs-26 fw-500" v-model="item.limitValue" placeholder="请输入限量值" />
                    </view>
                    <view class="rows rowsm pb-16">
                        <view class="col888 fs-26 fw-500 mr-10">执法依据:</view>
                        <input class="fs-26 fw-500" v-model="item.executionBasis" placeholder="请输入执法依据" />
                    </view>
                    <view class="rows rowsm pb-16">
                        <view class="col888 fs-26 fw-500 mr-10">检测方法:</view>
                        <input class="fs-26 fw-500" v-model="item.detectionMethod" placeholder="请输入检测方法" />
                    </view>
                </view>
            </view>
        </view>

        <view @tap="submit('publish')" class="w-320 h-88 br-16 fixed rowsc rowsm fs-36 colfff bg"
            style="bottom: 68rpx;right: 50rpx;">
            提交
        </view>
        <view @tap="submit('draft')" class="w-320 h-88 br-16 fixed rowsc rowsm fs-36 colfff bg"
            style="bottom: 68rpx;left: 50rpx;">
            草稿
        </view>
        <u-picker :show="showYearPicker" :columns="yearColumns" :defaultIndex="yearDefaultIndex" @confirm="yearConfirm"
            @cancel="showYearPicker = false" @close="showYearPicker = false" />
        <u-picker :show="showTypePicker" :columns="typeColumns" @confirm="typeConfirm" @cancel="showTypePicker = false"
            @close="showTypePicker = false" />
        <!-- 产品选择：使用 u-picker -->
        <u-picker :show="showProductPicker" :columns="productColumns" @confirm="productConfirm"
            @cancel="showProductPicker = false" @close="showProductPicker = false" />

        <!-- lsj-upload 插件 -->
        <lsj-upload ref="lsjUploadRef"></lsj-upload>
    </view>
</template>

<script>
import { addProductStandard, selectListData, PRODUCT_STANDARD_IMPORT_URL, exportExcelTemplate, exportWordTemplate } from '@/api/productStandard'
import request from '@/utils/request'
import appConfig from '@/config'
import navbarMixin from '@/common/navbarMixin'
export default {
    mixins: [navbarMixin],
    data() {
        return {
            yearColumns: [(() => {
                const currentYear = new Date().getFullYear()
                const years = []
                for (let i = currentYear + 20; i >= currentYear - 20; i--) {
                    years.push(i.toString())
                }
                return years
            })()],
            yearDefaultIndex: [0],
            showYearPicker: false,
            showTypePicker: false,
            showProductPicker: false,
            // 检测类型（数字字典）
            typeColumns: [[]],
            detectionTypeOptions: [], // {label, value}
            detectionDictType: 'product_monitor_type', // 假定字典类型，后端若不同请告知
            // 产品 picker 列数据
            productColumns: [[]],
            // 源数据用于 id/name 映射
            productListRaw: [],
            // 上传相关
            uploadedFiles: [], // 上传的文件列表
            uploadConfig: {
                url: PRODUCT_STANDARD_IMPORT_URL,
                name: 'file',
                header: {},
                formData: {}
            },
            lastUploadResp: null,
            // 检测标准数据
            detectionStandards: [], // 上传后返回的检测标准数据
            formData: {
                detectionType: '',
                year: '',
                productId: '',
                productName: ''
            }
        }
    },
    computed: {
        // 按产品分组检测标准数据
        groupedStandards() {
            const groups = {}
            this.detectionStandards.forEach(item => {
                const productName = item.productName
                if (!groups[productName]) {
                    groups[productName] = []
                }
                groups[productName].push(item)
            })
            return groups
        },
        // 获取所有产品名称
        productNames() {
            return Object.keys(this.groupedStandards)
        }
    },
    created() {
        this.loadProducts()
        this.loadDetectionTypes()
        // 规范上传地址：H5 走 /dev-api 代理，其它端走绝对地址，且带上 token
        // // #ifdef H5
        // this.uploadConfig.url = `${appConfig.baseUrl}/dev-api/forest/productStandard/importData`
        // // #endif
        this.uploadConfig.url = `${appConfig.baseUrl}/forest/productStandard/importData`
        const token = uni.getStorageSync('App-Token')
        if (token) {
            this.uploadConfig.header = Object.assign({}, this.uploadConfig.header, { 'Authorization': 'Bearer ' + token })
        }
        // 计算年份默认索引为当前年
        const years = this.yearColumns[0]
        const idx = years.indexOf(String(new Date().getFullYear()))
        this.yearDefaultIndex = [idx >= 0 ? idx : 0]
    },
    methods: {
        async loadDetectionTypes() {
            try {
                const res = await request({ url: `/system/dict/data/type/${this.detectionDictType}`, method: 'get' })
                const rows = Array.isArray(res) ? res : (Array.isArray(res?.data) ? res.data : [])
                this.detectionTypeOptions = rows.map(d => ({
                    label: d.dictLabel ?? d.label ?? d.name ?? '-',
                    value: d.dictValue ?? d.value ?? d.code ?? ''
                }))
                this.typeColumns = [this.detectionTypeOptions.map(i => i.label)]
            } catch (e) {
                // 失败则保持空，用户可手动输入或稍后重试
                this.typeColumns = [[]]
            }
        },
        async loadProducts() {
            try {
                const res = await selectListData()
                const list = Array.isArray(res) ? res : (Array.isArray(res?.data) ? res.data : [])
                // 兼容 {label,value} 或 {name,id}
                this.productListRaw = list.map(it => ({
                    id: it.value ?? it.id,
                    name: it.label ?? it.name ?? '-'
                }))
                this.productColumns = [this.productListRaw.map(it => it.name)]
            } catch (e) {
                console.error('加载产品列表失败:', e)
            }
        },
        productConfirm(e) {
            const idx = Array.isArray(e.indexs) ? e.indexs[0] : 0
            const item = this.productListRaw[idx]
            if (item) {
                this.formData.productId = item.id
                this.formData.productName = item.name
            }
            this.showProductPicker = false
        },
        yearConfirm(e) {
            this.formData.year = e.value[0]
            this.showYearPicker = false
        },
        typeConfirm(e) {
            const idx = Array.isArray(e.indexs) ? e.indexs[0] : 0
            const opt = this.detectionTypeOptions[idx]
            // 保存字典值与展示名
            this.formData.detectionType = opt ? opt.value : (e.value ? e.value[0] : '')
            this.formData.detectionTypeLabel = opt ? opt.label : (e.value ? e.value[0] : '')
            this.showTypePicker = false
        },
        // 触发选择并上传文件
        handleUpload() {
            this.$refs.lsjUploadRef.chooseFile({
                count: 5, // 最多选择5个文件
                size: 10, // 单个文件最大10MB
                multiple: true, // 允许多选
                formats: 'xlsx,xls,docx', // 只允许选择指定格式
                success: (files) => {
                    console.log('选择的文件:', files)
                    // 将新选择的文件添加到现有文件列表
                    this.uploadedFiles = [...this.uploadedFiles, ...files]
                    // 自动上传文件
                    this.autoUploadFiles(files)
                },
                fail: (error) => {
                    console.error('选择文件失败:', error)
                    uni.showToast({
                        title: '选择文件失败',
                        icon: 'none'
                    })
                }
            })
        },

        // 自动上传文件
        autoUploadFiles(newFiles) {
            newFiles.forEach(file => {
                this.uploadFile(file)
            })
        },

        uploadFile(file) {
            // 文件上传接口
            const uploadUrl = this.uploadConfig.url
            
            this.$refs.lsjUploadRef.upload({
                file: file,
                url: uploadUrl,
                name: this.uploadConfig.name,
                method: 'post',
                header: this.uploadConfig.header,
                formData: this.uploadConfig.formData,
                onprogress: (e) => {
                    file.status = 'progress'
                    file.progress = e.progress || 0
                    console.log('上传进度:', e)
                },
                success: (e) => {
                    file.status = 'success'
                    file.responseText = e.result || e.data
                    
                    // 处理上传成功返回的检测标准数据
                    try {
                        // 尝试从不同位置获取数据
                        let responseData = null
                        
                        // 1. 优先尝试 e.result
                        if (e.result) {
                            responseData = typeof e.result === 'string' ? JSON.parse(e.result) : e.result
                        }
                        
                        // 2. 尝试 e.data
                        if (!responseData && e.data) {
                            responseData = typeof e.data === 'string' ? JSON.parse(e.data) : e.data
                        }
                        
                        // 3. 如果e.data为空，尝试从e中直接获取
                        if (!responseData && e) {
                            responseData = e
                        }
                        
                        // 4. 尝试从e的其他属性获取
                        if (!responseData && e.response) {
                            responseData = typeof e.response === 'string' ? JSON.parse(e.response) : e.response
                        }
                        
                        if (responseData) {
                            // 尝试多种可能的数据结构
                            let standardsData = null
                            if (responseData && responseData.code === 200 && Array.isArray(responseData.data)) {
                                standardsData = responseData.data
                            } else if (Array.isArray(responseData)) {
                                standardsData = responseData
                            } else if (responseData && Array.isArray(responseData.data)) {
                                standardsData = responseData.data
                            } else if (responseData && responseData.data && Array.isArray(responseData.data.list)) {
                                standardsData = responseData.data.list
                            }
                            
                            if (standardsData && standardsData.length > 0) {
                                this.detectionStandards = standardsData
                            }
                        }
                    } catch (error) {
                        console.error('解析上传返回数据失败:', error)
                    }
                    
                    uni.showToast({
                        title: '文件上传成功',
                        icon: 'success'
                    })
                },
                fail: (e) => {
                    file.status = 'fail'
                    console.error('上传失败:', e)
                    uni.showToast({
                        title: '文件上传失败',
                        icon: 'none'
                    })
                }
            })
        },

        // 删除文件
        removeFile(index) {
            if (this.uploadedFiles && index > -1 && index < this.uploadedFiles.length) {
                const file = this.uploadedFiles[index]
                // 调用插件删除文件
                this.$refs.lsjUploadRef.deleted(file)
                // 从数组中移除
                this.uploadedFiles.splice(index, 1)
                // 重新赋值触发视图更新
                this.uploadedFiles = [...this.uploadedFiles]
            }
        },

        // 格式化文件大小
        formatSize(n) {
            if (!n && n !== 0) return ''
            const kb = n / 1024, mb = kb / 1024
            return mb >= 1 ? (mb.toFixed(1) + ' MB') : (Math.max(kb, 1).toFixed(0) + ' KB')
        },

        // 获取状态文本
        getStatusText(status) {
            switch (status) {
                case 'progress': return '上传中'
                case 'success': return '成功'
                case 'fail': return '失败'
                default: return '待上传'
            }
        },
        // 添加检测项目
        addItem(productName) {
            // 在当前产品分组下添加空的检测项目
            const newItem = {
                serialNumber: this.getNextSerialNumber(productName),
                inspectionItem: '',
                limitValue: '',
                executionBasis: '',
                detectionMethod: '',
                productName: productName,
                product: productName,
                isNew: true // 标记为新添加的项目
            }
            
            // 添加到对应产品分组
            if (!this.groupedStandards[productName]) {
                this.$set(this.groupedStandards, productName, [])
            }
            this.groupedStandards[productName].push(newItem)
            
            // 重新构建detectionStandards数组
            this.rebuildDetectionStandards()
            
            uni.showToast({
                title: '已添加新检测项目',
                icon: 'success'
            })
        },
        
        // 删除检测项目
        deleteItem(item, itemIndex, productName) {
            uni.showModal({
                title: '提示',
                content: '确定删除该检测项目吗？',
                success: (res) => {
                    if (res.confirm) {
                        // 从当前分组中删除
                        if (this.groupedStandards[productName]) {
                            this.groupedStandards[productName].splice(itemIndex, 1)
                            // 重新构建detectionStandards数组
                            this.rebuildDetectionStandards()
                        }
                        uni.showToast({ title: '删除成功', icon: 'success' })
                    }
                }
            })
        },
        
        // 重新构建detectionStandards数组
        rebuildDetectionStandards() {
            const newStandards = []
            Object.keys(this.groupedStandards).forEach(productName => {
                newStandards.push(...this.groupedStandards[productName])
            })
            this.detectionStandards = newStandards
        },
        
        // 获取下一个序号
        getNextSerialNumber(productName) {
            const items = this.groupedStandards[productName] || []
            if (items.length === 0) return 1
            
            // 找到最大序号
            let maxNumber = 0
            items.forEach(item => {
                const num = parseInt(item.serialNumber) || 0
                if (num > maxNumber) {
                    maxNumber = num
                }
            })
            return maxNumber + 1
        },
        
        async submit(status) {
            const { year, detectionType, productId, productName } = this.formData
            if (!year) return uni.showToast({ title: '请选择年份', icon: 'none' })
            if (!detectionType) return uni.showToast({ title: '请选择检测类型', icon: 'none' })

            // 检查是否有文件还在上传中
            const uploadingFiles = this.uploadedFiles.filter(f => f.status === 'progress')
            if (uploadingFiles.length > 0) {
                uni.showToast({
                    title: '还有文件正在上传，请稍候',
                    icon: 'none'
                })
                return
            }

            // 检查是否有上传失败的文件
            const failedFiles = this.uploadedFiles.filter(f => f.status === 'fail')
            if (failedFiles.length > 0) {
                uni.showToast({
                    title: '有文件上传失败，请重新上传',
                    icon: 'none'
                })
                return
            }

            // 验证检测项目数据
            if (this.detectionStandards.length === 0) {
                uni.showToast({ title: '请添加检测标准数据', icon: 'none' })
                return
            }
            
            // // 验证每个检测项目的必填字段
            // for (let i = 0; i < this.detectionStandards.length; i++) {
            //     const item = this.detectionStandards[i]
            //     if (!item.inspectionItem) {
            //         uni.showToast({ title: `第${i + 1}项检测项目不能为空`, icon: 'none' })
            //         return
            //     }
            //     if (!item.limitValue) {
            //         uni.showToast({ title: `第${i + 1}项限量值不能为空`, icon: 'none' })
            //         return
            //     }
            //     if (!item.executionBasis) {
            //         uni.showToast({ title: `第${i + 1}项执法依据不能为空`, icon: 'none' })
            //         return
            //     }
            //     if (!item.detectionMethod) {
            //         uni.showToast({ title: `第${i + 1}项检测方法不能为空`, icon: 'none' })
            //         return
            //     }
            // }

            const payload = { 
                year, 
                detectionType, 
                productId, 
                productName,
                status: status,
                // 将检测标准数据转换为PC版格式
                tableData: JSON.stringify(this.detectionStandards.map(item => ({
                    productStandardDetailId: item.productStandardDetailId || Date.now() + Math.random(),
                    productId: item.productId || null,
                    product: item.productName || item.product || '',
                    index: item.serialNumber || 1,
                    item: item.inspectionItem || '',
                    limit: item.limitValue || '',
                    basis: item.executionBasis || '',
                    method: item.detectionMethod || '',
                    action: 'delete' // 默认标记为可删除
                }))),
                // 确保ext1字段也包含数据（兼容性）
                ext1: JSON.stringify(this.detectionStandards)
            }
            try {
                uni.showLoading({ title: '提交中...' })
                await addProductStandard(payload)
                uni.hideLoading()
                uni.showToast({ title: '提交成功', icon: 'success' })
                setTimeout(() => { uni.navigateBack() }, 600)
            } catch (e) {
                uni.hideLoading()
                console.error('新增失败:', e)
                uni.showToast({ title: '提交失败', icon: 'none' })
            }
        }
    }
}
</script>

<style>
.mine-navbar-bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 1;
}

.upload-section {
    display: flex;
    flex-direction: column;
    gap: 16rpx;
}

.upload-note {
    font-size: 24rpx;
    color: #999;
}

.file-list {
    margin-top: 20rpx;
}

.file-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16rpx;
    background: #f8f9fa;
    border-radius: 12rpx;
    margin-bottom: 12rpx;
}

.file-info {
    display: flex;
    align-items: center;
    flex: 1;
    gap: 12rpx;
}

.file-name {
    font-size: 26rpx;
    color: #333;
    flex: 1;
}

.file-size {
    font-size: 24rpx;
    color: #999;
}

.file-status {
    margin-right: 16rpx;
}

.status-success {
    font-size: 24rpx;
    color: #4caf50;
}

.status-progress {
    font-size: 24rpx;
    color: #2196f3;
}

.status-fail {
    font-size: 24rpx;
    color: #f44336;
}

.status-pending {
    font-size: 24rpx;
    color: #999;
}

.product-section {
    margin-bottom: 30rpx;
}

.product-section:last-child {
    margin-bottom: 0;
}

/* 输入框样式 */
input {
    border: none;
    outline: none;
    background: transparent;
    flex: 1;
    min-width: 0;
}

input::placeholder {
    color: #ccc;
    font-size: 24rpx;
}
</style>
